package thread;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;

public class DrawThread extends Thread {
	private Graphics g;
	private int drawW, drawH;
	private ArrayList<Ball> balls;

	public DrawThread(Graphics g, ArrayList<Ball> balls, int w, int h) {
		this.g = g;
		this.drawW = w;
		this.drawH = h;
		this.balls = balls;
	}

	@Override
	public void run() {
		/**
		 * 由于线程是并发的，即本质上交替执行 所以通过利用一个线程来专门绘制，另一个线程来改变小球坐标 同时利用缓冲绘图来增加流畅性
		 */
		super.run();
		while (true) {
			BufferedImage bufferI = new BufferedImage(drawW, drawH, BufferedImage.TYPE_INT_RGB);
			Graphics bufferG = bufferI.getGraphics();

			bufferG.setColor(Color.yellow);
			for (int i = 0; i < balls.size(); ++i) {
				Ball ball = balls.get(i);
				bufferG.fillOval(ball.x, ball.y, ball.r, ball.r);
				ball.x += 3;
			}
			g.drawImage(bufferI, 0, 0, null);
			_sleep(100);
			g.setColor(Color.black);
			g.fillRect(0, 0, drawW, drawH);
		}
	}

	private void _sleep(long millis) {
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
